import { defineStore } from 'pinia';
import { store } from '/@/store';
import { getDictItems } from '/@/api/common/api';

interface DicState {
  dicData: {};
}

export const useDicStore = defineStore({
  id: 'app-dic',
  state: (): DicState => ({
    dicData: {},
  }),
  getters: {},
  actions: {
    setDicData(key: string, list: any[]) {
      this.dicData[key] = list;
    },
    async getDicData(key: string) {
      const data = this.dicData[key];
      if (data) {
        return data;
      } else {
        const dictCode = key;
        const result = await getDictItems(dictCode);

        if (result.length > 0) {
          const res = result.map((item) => ({ ...item, label: item.text }));
          console.log('------- 从DB中获取到了字典-------dictCode : ', dictCode, res);
          this.setDicData(dictCode, res);
          return res;
        } else {
          console.error('getDictItems not data : ', result);
          return {};
        }
      }
    },
  },
});

// Need to be used outside the setup
export function useDicStoreWithOut() {
  return useDicStore(store);
}
